﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shop.Managers;
using Data.Mappers;
using Shop.Mappers;

namespace Shop.Areas.Admin.Controllers
{
    public class CategoriesController : Controller
    {
        private IManager<Entity.Categories.Category> managerCategories;
        private IManager<Entity.Products.Product> managerProducts;
        private IWebMapper mapper;

        public CategoriesController(IManager<Entity.Products.Product> managerProducts, IManager<Entity.Categories.Category> managerCategories, IWebMapper mapper)
        {
            this.managerCategories = managerCategories;
            this.managerProducts = managerProducts;
            this.mapper = mapper;
        }

        public ActionResult Index()
        {
            return View(mapper.Wrapper(managerCategories.All.ToList()));
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Shop.Models.Category category)
        {
            if (ModelState.IsValid)
            {
                managerCategories.Add(mapper.Wrapper(category));
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        [HttpGet]
        public ActionResult Update(string IdCategory)
        {
            Entity.Categories.Category category = managerCategories.Find(Int32.Parse(IdCategory));
            return View(mapper.Wrapper(category));
        }

        public ActionResult Update(Shop.Models.Category category)
        {
            List<Entity.Products.Product> products = managerProducts.All.Where(x => x.Categories.Where(y => y.Id == category.Id).Count() != 0).ToList();

            category.Products = products;

            managerCategories.Update(mapper.Wrapper(category));

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Delete(string IdCategory)
        {
            managerCategories.Remove(Int32.Parse(IdCategory));
            return RedirectToAction("Index");
        }
    }
}
